package com.eascs.fp.uc.controller;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.common.service.ILoanInfoService;
import com.eascs.admin.common.vo.WeChatParams;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.fp.common.entity.MemberEntity;
import com.eascs.fp.common.entity.MemberOperateLogEntity;
import com.eascs.fp.common.security.MD5;
import com.eascs.fp.common.vo.ModelResult;
import com.eascs.fp.operateLog.server.OperateLogService;
import com.eascs.fp.uc.server.MemberService;
import com.eascs.fp.uc.untils.CusAccessObjectUtil;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.ViewContext;

@RequestMapping("/uc/rest")
@RestController
public class MemberRestController extends BaseRestController {
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	private MemberService memberService;

	@Autowired
	private OperateLogService operateLogService;

	@Reference
	ILoanInfoService iLoanInfoService;

	public static void setSession(HttpServletRequest request, MemberEntity member) {
		HttpSession session = request.getSession();
		String sessionId = session.getId();
		session.removeAttribute(sessionId);
		session.setAttribute(sessionId, member);
	}

	public static ModelResult<MemberEntity> isLogin(HttpServletRequest request) {
		ModelResult<MemberEntity> result = new ModelResult<>();
		try {
			HttpSession session = request.getSession();
			Object obj = session.getAttribute(session.getId());
			if (obj != null) {
				result.withModel((MemberEntity) obj);
			}
		} catch (Exception e) {
			result.withError("LoginRestController.isLogin", "session获取登陆用户失败");
			e.printStackTrace();
		}
		return result;
	}

	@RequestMapping(value = "/login")
	@ResponseBody
	public BaseRestResult<ModelResult<Boolean>> login(HttpServletRequest request, HttpServletResponse response,
			String account, String password) {
		ModelResult<Boolean> result = new ModelResult<>();
		if (account.isEmpty() || password.isEmpty()) {
			result.withError("param is null", "登陆参数不能为空");
			return BaseRestResult.buildRestResult(result);
		}
		String pw = MD5.md5Encode(password.trim());
		MemberEntity entity = new MemberEntity(account, pw);
		ModelResult<MemberEntity> modelResult = memberService.queryMemberEntity(entity);
		MemberEntity member = modelResult.getModel();
		if (member != null) {
			try {
				String ip = CusAccessObjectUtil.getIpAddress(request);
				MemberOperateLogEntity logEntity = new MemberOperateLogEntity();
				logEntity.setCreateTime(new Date());
				logEntity.setOperater(member.getAccount());
				logEntity.setLocation(ip);
				logEntity.setOperateDetail(request.getRequestURL().toString());
				operateLogService.insertMemberOperateLog(logEntity);
			} catch (Exception e) {
				logger.info("request.controller.error:/uc/login,exception:{}", e.getMessage());
			}
			MemberRestController.setSession(request, member);
			result.withModel(true);
			return BaseRestResult.buildRestResult(result);
		}
		result.withError("param error", "账号或密码不正确");
		return BaseRestResult.buildRestResult(result);
	}

	@RequestMapping(value = "/register")
	@ResponseBody
	public BaseRestResult<ModelResult<Boolean>> register(HttpServletRequest request, String mobile, String password) {
		ModelResult<Boolean> result = new ModelResult<>();
		if (mobile.isEmpty() || password.isEmpty()) {
			result.withError("param is null", "登陆参数不能为空");
			return BaseRestResult.buildRestResult(result);
		}
		MemberEntity member = new MemberEntity();
		member.setAccount(mobile);
		member.setMobile(mobile);
		String pw = MD5.md5Encode(password.trim());
		ModelResult<MemberEntity> queryResult = memberService.queryMemberEntity(member);
		if (!queryResult.isSuccess() || queryResult.getModel() != null) {
			result.withError("user is exist", "该用户已注册");
			return BaseRestResult.buildRestResult(result);
		}
		member.setPassword(pw);
		ModelResult<MemberEntity> modelResult = memberService.insertMemberEntity(member);
		if (modelResult.isSuccess() && modelResult.getModel() != null) {
			MemberEntity model = modelResult.getModel();
			if (model != null) {
				MemberRestController.setSession(request, member);
				result.withModel(true);
				return BaseRestResult.buildRestResult(result);
			}
		}
		result.withError("register error", "注册失败");
		return BaseRestResult.buildRestResult(result);
	}

	@RequestMapping(value = "/forgetPassword")
	@ResponseBody
	public BaseRestResult<ModelResult<Boolean>> forgetPassword(HttpServletRequest request, String mobile,
			String password) {
		ModelResult<Boolean> result = new ModelResult<>();
		if (password.isEmpty()) {
			result.withError("param is null", "参数不能为空");
			return BaseRestResult.buildRestResult(result);
		}
		MemberEntity memberEntity = new MemberEntity();

		ModelResult<MemberEntity> queryResult = memberService.queryMemberEntity(memberEntity);
		memberEntity.setMobile(mobile);
		memberEntity.setAccount(queryResult.getModel().getAccount());
		if (!queryResult.isSuccess() || queryResult.getModel() == null) {
			result.withError("user not exist", "该用户不存在");
			return BaseRestResult.buildRestResult(result);
		}
		String pw = MD5.md5Encode(password.trim());
		memberEntity.setPassword(pw);
		ModelResult<Boolean> modelResult = memberService.updateMemberEntity(memberEntity);
		if (modelResult.isSuccess() && modelResult.getModel() != null) {
			MemberEntity member = queryResult.getModel();
			member.setPassword(pw);
			MemberRestController.setSession(request, member);
			result.withModel(true);
			return BaseRestResult.buildRestResult(result);
		}
		result.withError("forgetPassword error", "修改失败");
		return BaseRestResult.buildRestResult(result);
	}

	@RequestMapping(value = "/alertPassword")
	@ResponseBody
	public BaseRestResult<ModelResult<Boolean>> alertPassword(HttpServletRequest request, String mobile,
			String oldPassword, String newPassword) {

		ModelResult<Boolean> result = new ModelResult<>();
		if (oldPassword.isEmpty() || newPassword.isEmpty()) {
			result.withError("param is null", "参数不能为空");
			return BaseRestResult.buildRestResult(result);
		}
		MemberEntity memberEntity = new MemberEntity();
		memberEntity.setMobile(mobile);
		ModelResult<MemberEntity> queryResult = memberService.queryMemberEntity(memberEntity);
		MemberEntity model = queryResult.getModel();

		String oldPwd = MD5.md5Encode(oldPassword.trim());
		String newPwd = MD5.md5Encode(newPassword.trim());
		if (!oldPwd.equals(model.getPassword())) {
			result.withError("password is wrong", "旧密码不正确");
			return BaseRestResult.buildRestResult(result);
		}
		memberEntity.setPassword(newPwd);
		memberEntity.setAccount(model.getAccount());
		ModelResult<Boolean> modelResult = memberService.updateMemberEntity(memberEntity);
		if (modelResult.isSuccess() && modelResult.getModel() != null) {
			MemberEntity member = queryResult.getModel();
			member.setPassword(newPwd);
			MemberRestController.setSession(request, member);
			result.withModel(true);
			return BaseRestResult.buildRestResult(result);
		}
		result.withError("forgetPassword error", "修改失败");
		return BaseRestResult.buildRestResult(result);
	}

	@RequestMapping(value = "/modifyPhone")
	@ResponseBody
	public BaseRestResult<ModelResult<Boolean>> modifyPhone(HttpServletRequest request, String oldmobile,
			String newmobile) {
		// System.out.println(oldmobile+newmobile);
		ModelResult<Boolean> result = new ModelResult<>();
		if (oldmobile.isEmpty() || newmobile.isEmpty()) {
			result.withError("param is null", "参数不能为空");
			return BaseRestResult.buildRestResult(result);
		}
		MemberEntity memberEntity = new MemberEntity();
		memberEntity.setMobile(oldmobile);
		ModelResult<MemberEntity> queryResult = memberService.queryMemberEntity(memberEntity);
		MemberEntity model = queryResult.getModel();// 查询成功,返回该手机号码用户的所有信息实体类
		//
		// String oldPwd=MD5.md5Encode(oldPassword.trim());
		// String newPwd=MD5.md5Encode(newPassword.trim());
		// if (!oldPwd.equals(model.getPassword())) {
		// result.withError("password is wrong", "旧密码不正确");
		// return BaseRestResult.buildRestResult(result);
		// }
		memberEntity.setMobile(newmobile);
		memberEntity.setAccount(model.getAccount());
		ModelResult<Boolean> modelResult = memberService.updateMemberEntity(memberEntity);
		if (modelResult.isSuccess() && modelResult.getModel() != null) {
			MemberEntity member = queryResult.getModel();
			member.setMobile(newmobile);
			MemberRestController.setSession(request, member);
			result.withModel(true);
			return BaseRestResult.buildRestResult(result);
		}
		result.withError("modifyphone error", "修改失败");
		return BaseRestResult.buildRestResult(result);
	}

	@RequestMapping("/scheduelInqueryResult") // 进入查询进度查询结果页面

	public HtmlRestResult getInqueryResult(String username, String idcard, String tel, WeChatParams params) {
		
		// System.out.println(username);
		// System.out.println(tel);
		// System.out.println(idcard);
		params.setName(username);
		params.setPhone(tel);
		params.setIdCard(idcard);
		String scheduleState; // 存放提示信息
		com.eascs.admin.common.vo.ModelResult<String> model = iLoanInfoService.getLoanApplyStatus(params);// 根据参数查询进度
		if (model.getErrMsg() != null) {
			if (model.getErrMsg().equals("无贷款单号")) {
				scheduleState = "您未有审批中的贷款申请，如您已申请请联系您的信贷经理。";
				ViewContext.put("scheduleState", scheduleState);
				return HtmlRestResult.html("/uc/InqueryResult");
			}
		}
		if (model.getModel() != null) {
			if (model.getModel().equals("新建")) {
				scheduleState = "待提交审核";
				ViewContext.put("scheduleState", scheduleState);
				return HtmlRestResult.html("/uc/InqueryResult");
			}
			if (model.getModel().equals("作废")) {
				scheduleState = "未通过";
				ViewContext.put("scheduleState", scheduleState);
				return HtmlRestResult.html("/uc/InqueryResult");

			}
			if (model.getModel().equals("征信中") || model.getModel().equals("征信完成") || model.getModel().equals("内审中")
					|| model.getModel().equals("内审完成")) {
				scheduleState = "贷款审核中";
				ViewContext.put("scheduleState", scheduleState);
				return HtmlRestResult.html("/uc/InqueryResult");
			}
			if (model.getModel().equals("申报中")) {
				scheduleState = "银行放款审核中";
				ViewContext.put("scheduleState", scheduleState);
				return HtmlRestResult.html("/uc/InqueryResult");

			}
			if (model.getModel().equals("已放款") || model.getModel().equals("还款完成") || model.getModel().equals("逾期")
					|| model.getModel().equals("代偿")) {
				scheduleState = "已放款";
				ViewContext.put("scheduleState", scheduleState);
				return HtmlRestResult.html("/uc/InqueryResult");

			}
			if (model.getModel().equals("银行已拒绝")) {
				scheduleState = "未通过银行审核";
				ViewContext.put("scheduleState", scheduleState);
				return HtmlRestResult.html("/uc/InqueryResult");
			}

		}

		return null;
	}
}
